package com.sh.data.engine.domain.shims.postgresql.util;

import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.ast.statement.SQLCreateTableStatement;
import com.alibaba.druid.sql.parser.SQLParserUtils;
import com.alibaba.druid.sql.parser.SQLStatementParser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;

/**
 * @author: mengzheng.mhc
 * @date: 2024/6/5 17:01
 */
@Slf4j
public class PostgreSqlParserUtil {

    /**
     * 从用户提交的建表语句解析出表明
     *
     * @param sql
     * @return
     */
    public static Pair<String, String> getCreateTableName(String sql) {
        SQLStatementParser sqlStatementParser =
            SQLParserUtils.createSQLStatementParser(sql, DbType.postgresql);
        try {
            SQLCreateTableStatement sqlCreateTableStatement = sqlStatementParser.parseCreateTable();
            log.info(sqlCreateTableStatement.toString());
            String schema = sqlCreateTableStatement.getSchema();
            String tableName = sqlCreateTableStatement.getTableName();
            return Pair.of(removeDoubleQuotes(schema), removeDoubleQuotes(tableName));
        } catch (Exception e) {
            log.error("{} 获取表名异常 {}", sql, e.getMessage());
        }
        return Pair.of("", "");
    }

    // 移除双引号
    public static String removeDoubleQuotes(String str) {
        if (StringUtils.isNotEmpty(str)) {
            return str.replaceAll("\"", "");
        }
        return "";
    }
}
